package com.lingnan.wanxiangxinxun.util;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


//阿里云OSS工具类
@Slf4j
@Component
public class AliOSSUtils {

//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint ;
//    @Value("${aliyun.oss.accessKeyId}")
//    private String accessKeyId ;
//    @Value("${aliyun.oss.accessKeySecret}")
//    private String accessKeySecret ;
//    @Value("${aliyun.oss.bucketName}")
//    private String bucketName ; //存储空间的名字

    @Autowired
    private AliOSSProperties aliOSSProperties;


    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file, String directoryName) throws IOException {

        String endpoint = aliOSSProperties.getEndpoint(); //阿里云OSS的endpoint，比如https://oss-cn-hangzhou.aliyuncs.com
        String accessKeyId = aliOSSProperties.getAccessKeyId(); //阿里云的KeyID
        String accessKeySecret = aliOSSProperties.getAccessKeySecret(); //阿里云的密钥
        String bucketName = aliOSSProperties.getBucketName(); //存储空间的名字

        if(directoryName == null){ directoryName = "";}

        //1、获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        //2、避免文件覆盖（使用UUID）
        String originalFileName = file.getOriginalFilename();
        String filenameWithoutSuffix = originalFileName.substring(0, originalFileName.lastIndexOf('.')); // 截取不包含文件后缀名的部分
        String suffix = originalFileName.substring(originalFileName.lastIndexOf(".")); // 截取文件后缀名
        String fileName = directoryName + filenameWithoutSuffix + UUID.randomUUID().toString() + suffix;

        //3、上传文件到OSS!!!
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret); // 创建OSSClient实例
        ossClient.putObject(bucketName,fileName,inputStream);

        //4、获取文件访问路径
        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        //endpoint.split("//")[0] 获取协议部分（例如 https:）。
        //endpoint.split("//")[1] 获取域名部分（例如 oss-cn-hangzhou.aliyuncs.com）
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        //5、关闭ossClient
        ossClient.shutdown();
        return url; //6、返回上传到oss的路径

    }



    /**
     * 删除某个对象
     */
    public void deleteObject(String fullPath){

        String endpoint = aliOSSProperties.getEndpoint(); //阿里云OSS的endpoint，比如https://oss-cn-hangzhou.aliyuncs.com
        String accessKeyId = aliOSSProperties.getAccessKeyId(); //阿里云的KeyID
        String accessKeySecret = aliOSSProperties.getAccessKeySecret(); //阿里云的密钥
        String bucketName = aliOSSProperties.getBucketName(); //存储空间的名字

        //传进来的fullPath一般格式是这样："https://存储桶名字.阿里云oss服务器地址/目录名(可以为空也可以多层)/文件名"
        String fileName1 = fullPath.split("//")[1]; //截取 “存储桶名字.阿里云oss服务器地址/目录名(可以为空也可以多层)/文件名” 这一部分
        String fileName2 = fileName1.substring(fileName1.indexOf("/")+1); //截取 “目录名/文件名” 这一部分

        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret); // 创建OSSClient实例
        try {
            log.info("删除oss文件，要删除的文件为：{}", fileName2);
            ossClient.deleteObject(bucketName, fileName2);// 删除文件(存储桶的名字+文件路径，文件路径例如"myTest/test.txt")
        } catch (OSSException e) {
            System.out.println("阿里云oss删除对象发生错误，信息为:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }



    /**
     * 删除指定前缀的文件
     * @param prefix 文件前缀
     */
    public void deleteObjectsWithPrefix(String prefix) {

        String endpoint = aliOSSProperties.getEndpoint(); //阿里云OSS的endpoint，比如https://oss-cn-hangzhou.aliyuncs.com
        String accessKeyId = aliOSSProperties.getAccessKeyId(); //阿里云的KeyID
        String accessKeySecret = aliOSSProperties.getAccessKeySecret(); //阿里云的密钥
        String bucketName = aliOSSProperties.getBucketName(); //存储空间的名字
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret); // 创建OSSClient实例


        try {
            // 列举所有包含指定前缀的文件并删除。
            String nextMarker = null;
            ObjectListing objectListing = null;
            do {
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName)
                        .withPrefix(prefix)
                        .withMarker(nextMarker);

                objectListing = ossClient.listObjects(listObjectsRequest);
                if (objectListing.getObjectSummaries().size() > 0) {
                    List<String> keys = new ArrayList<String>();
                    for (OSSObjectSummary s : objectListing.getObjectSummaries()) {
                        System.out.println("key name: " + s.getKey());
                        keys.add(s.getKey());
                    }
                    DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url");
                    DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
                    List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
                    try {
                        for(String obj : deletedObjects) {
                            String deleteObj =  URLDecoder.decode(obj, "UTF-8");
                            System.out.println(deleteObj);
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                nextMarker = objectListing.getNextMarker();
            } while (objectListing.isTruncated());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }



    /**
     * 重命名文件
     */
    public void renameObject(String fullPath){

        String endpoint = aliOSSProperties.getEndpoint(); //阿里云OSS的endpoint，比如https://oss-cn-hangzhou.aliyuncs.com
        String accessKeyId = aliOSSProperties.getAccessKeyId(); //阿里云的KeyID
        String accessKeySecret = aliOSSProperties.getAccessKeySecret(); //阿里云的密钥
        String bucketName = aliOSSProperties.getBucketName(); //存储空间的名字

        String sourceKey1 = fullPath.split("//")[1]; //截取 “存储桶名字.阿里云oss服务器地址/目录名(可以为空也可以多层)/文件名” 这一部分
        String sourceKey2 = sourceKey1.substring(sourceKey1.indexOf("/")+1); //截取 “目录名/文件名” 这一部分

        // 目标Object的完整路径（如：img/client/example.txt）
        String destinationKey = sourceKey2.replaceFirst("temp_",  "");

        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret); // 创建OSSClient实例
        try {
            // 将bucketName下的temp_example.txt拷贝至同一Bucket下的example.txt
            ossClient.copyObject(bucketName, sourceKey2, bucketName, destinationKey);

            // 删除temp_example.txt
            ossClient.deleteObject(bucketName, sourceKey2);
        } catch (OSSException e) {
            System.out.println("阿里云oss操作发生错误，信息为:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


}
